package com.ruoyi.dataSet.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.dataSet.DTO.DatasetCreateRequest;
import com.ruoyi.dataSet.service.DatasetService;
import com.ruoyi.system.domain.DsZsk;
import com.ruoyi.system.service.IDsZskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.View;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

//@Anonymous
@RestController
@RequestMapping("/dataset")
public class DatasetController {

    @Autowired
    private DatasetService datasetService;

    @Autowired
    private IDsZskService zskService;
    @Autowired
    private View error;

    // 创建知识库
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:add')")
    public String createDataset(@RequestBody DatasetCreateRequest request) {
        try {
            String name = request.getName();
            Long teacherId = request.getTeacherId();
            DsZsk zsk = new DsZsk();
            zsk.setZskName(name);
            zsk.setTeacherId(teacherId);
            zskService.insertDsZsk(zsk);
            return datasetService.createDataset(request);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 获取知识库列表
    // 获取知识库列表
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:list')")
    public String getDatasets(@RequestParam String page,
                              @RequestParam String limit,
                              @RequestParam(required = false) String teacherId) {
        try {
            // 1. 从dify获取原始知识库列表
            String difyResponse = datasetService.getDatasets(page, limit);

            // 如果没有传入teacherId，直接返回原始结果
            if (teacherId == null || teacherId.isEmpty()) {
                return "未获取到知识库!";
            }

            // 2. 从本地数据库查询该教师创建的所有知识库
            Long teacherIdLong = Long.parseLong(teacherId);
            DsZsk zsk = new DsZsk();
            zsk.setTeacherId(teacherIdLong);
            List<DsZsk> teacherZsks = zskService.selectDsZskList(zsk);
            Set<String> teacherZskNames = teacherZsks.stream()
                .map(DsZsk::getZskName)
                .collect(Collectors.toSet());

            // 3. 解析dify返回的json
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(difyResponse);
            JsonNode datasetsNode = rootNode.get("data");

            // 4. 创建一个新的数组，只包含当前教师的知识库
            ArrayNode filteredDatasets = mapper.createArrayNode();

            if (datasetsNode != null && datasetsNode.isArray()) {
                for (JsonNode dataset : datasetsNode) {
                    String datasetName = dataset.get("name").asText();
                    // 如果知识库名称在教师创建的知识库名称集合中，则添加到结果中
                    if (teacherZskNames.contains(datasetName)) {
                        filteredDatasets.add(dataset);
                    }
                }
            }

            // 5. 创建新的响应JSON
            ObjectNode resultNode = mapper.createObjectNode();
            resultNode.set("data", filteredDatasets);
            resultNode.put("has_more", rootNode.get("has_more").asBoolean());
            resultNode.put("limit", rootNode.get("limit").asInt());
            resultNode.put("total", filteredDatasets.size());
            resultNode.put("page", rootNode.get("page").asInt());

            return mapper.writeValueAsString(resultNode);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }


    // 删除知识库
    @DeleteMapping("/delete/{datasetId}")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:delete')")
    public String deleteDataset(@PathVariable String datasetId) {
        try {
            return datasetService.deleteDataset(datasetId);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }

    // 获取知识库的状态
    @PostMapping("/status")
    @PreAuthorize("@ss.hasPermi('deepSeek:dataset:status')")
    public String getDatasetStatus(@RequestBody DatasetCreateRequest request) {
        try {
            String datasetId = request.getDatasetId();
            return datasetService.getDatasetStatus(datasetId);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
}
